package com.tusuo.stds.ui.question;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.LinearLayout;

import com.tusuo.stds.util.Utils;

/**
 * @author J.Huang
 * @version 1.0
 *
 */

public class CustomLinearLayout extends LinearLayout {

    private ISwipeablePresenter mPresenter;

    public CustomLinearLayout(Context context) {
        super(context);
    }

    public CustomLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomLinearLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    // 坐标
    private float xLast, yLast;

    private boolean mFlag = false;

    private static final int SWIPE_THRESHOLD = 100;

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                xLast = ev.getX();
                yLast = ev.getY();
                break;
            case MotionEvent.ACTION_MOVE:
//                int x = 0;
//                break;
//            case MotionEvent.ACTION_UP:
                final float curX = ev.getX();
                final float curY = ev.getY();

                // 滑动距离
                float xDistance, yDistance;
                xDistance = curX - xLast;
                yDistance = curY - yLast;

                if (Math.abs(xDistance) > Math.abs(yDistance)) {
                    if (mFlag) {
                        mFlag = !mFlag;
                        break;
                    }
                    mFlag = !mFlag;

                    if (mPresenter != null) {
                        if (xDistance > SWIPE_THRESHOLD) {
                            if (Utils.UI.isFastSwipe()) {
                                return false;
                            }
                            mPresenter.toLastQuestion();
                        } else if (xDistance < -SWIPE_THRESHOLD) {
                            if (Utils.UI.isFastSwipe()) {
                                return false;
                            }
                            mPresenter.toNextOldQuestion();
                        }
                    }

                    return false;
                }
                break;
            default:
                break;
        }

        return super.onInterceptTouchEvent(ev);
    }

    public void setPresenter(ISwipeablePresenter presenter) {
        mPresenter = presenter;
    }
}
